#-*- coding:UTF-8 -*-
__author__ = 'Frank Yang <frankyang418@gmail.com>'
__date__ = "13-5-16 上午10:23"
__doc__ = u""
from lib.database import Base


def parse_obj_from_form(obj, form):
    """
    注意：此函数不对Base类的实例进行赋值操作，即仅对一些基本数据类型进行赋值，如：str，int，bool等
    Base的实例需手动进行赋值

    :param obj:
    :param form:
    """
    for attr in dir(obj):
        if not attr.startswith('_') and 'query' not in attr and 'metadata' not in attr and isinstance(attr,
                                                                                                      str):
            try:
                value = getattr(getattr(form, attr), 'data')
                if not isinstance(value, Base):
                    setattr(obj, attr, getattr(getattr(form, attr), 'data'))
            except AttributeError:
                pass


def setting_from_objects(tornado_conf, app_conf):
    """
    从两个配置文件中读取配置
    app_conf将覆盖tornado_conf
    :param tornado_conf: Tornado配置
    :param app_conf: 应用配置
    :return: dict
    """
    setting = dict()
    for key in dir(tornado_conf):
        if key.isupper():
            setting[key.lower()] = getattr(tornado_conf, key)
    for key in dir(app_conf):
        if key.isupper():
            setting[key.lower()] = getattr(app_conf, key)
    return setting


def md5(src):
    u"""
    MD5加密
    :param src:
    :return:
    """
    import hashlib

    return hashlib.md5(src).hexdigest().upper()


def create_captcha(length=4):
    def generate(length):
        u"""
        生成随机字符串
        :param length:字符串长度
        :return: 字符串
        """
        import random

        chars = '0123456789'
        chars = [x for x in chars]
        ret_str = ''
        for i in range(0, length, 1):
            ret_str += chars[random.randint(0, len(chars) - 1)]
        return ret_str

    from PIL import Image, ImageFont, ImageDraw
    import os

    font_file = os.path.join(os.path.dirname(__file__), 'MONACO.TTF')
    font = ImageFont.truetype(font_file, 22)
    chars = generate(length)
    img = Image.new('RGB', (20 * length, 40), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    draw.text((10, 5), chars, font=font, fill=(0, 0, 0))
    del draw
    return chars, img
